package com.club.controller;

import com.club.service.RedisService;
import com.club.util.CaptchaUtil;
import com.club.util.Result;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("captcha")
@CrossOrigin
public class CaptchaController {
    @Autowired
    CaptchaUtil captchaUtil;
    @Autowired
    RedisService redisService;

    @RequestMapping("base")
    public Result getCaptcha(HttpServletResponse response) {
        String[] arr = captchaUtil.getImage();
        String key = arr[0];
        String base64 = arr[1];
//        Cookie cookie = new Cookie("captchakey", key);
//        response.addCookie(cookie);
        return Result.success("已经更新验证码", key+"+data:image/jpeg;base64," + base64);
    }
    @RequestMapping("check")
    public Result checkCaptcha(HttpServletRequest request,@RequestParam("captchaCode") String captchaCode) {
        Cookie[] cookies = request.getCookies();
        String key = null;
        for (Cookie cookie : cookies){
            if (cookie.getName().equals("captchakey")){
                key = cookie.getValue();
                break;
            }
        }
        if (key == null) {
            return Result.error(400,"请求参数异常");
        }
        String code=(String) redisService.get(key);
        if (code==null){
            return Result.error(201,"验证码已过期");
        }
        if (captchaCode.equals(code)){
            return Result.success("验证码正确",true);
        }
        return Result.error(400,"验证码错误");
    }
}
